import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import Popup from '../../components/Popup/Popup';
import parseQuery from '../../utils/parseQuery';
import { bindWechat } from '../../../api/wechat';

class WebBind extends Component {
  constructor (props) {
    super(props);
    this.state = {
      popupVisible: false,
      bindingStatus: 0,
      countdown: 5,
    };
    this.getUserInfo = this.getUserInfo.bind(this);
  }
  componentDidMount () {
    this.getUserInfo();
  }

  async getUserInfo () {
    const search = decodeURIComponent(this.props.location.search);
    const query = parseQuery(search.slice(1));
    const { code } = query;
    const params = {
      code,
      visitBy: 'web',
    };
    const response = await bindWechat(params);
    if (response.code === 1) {
      this.setState({
        popupVisible: true,
        bindingStatus: 1,
      });
      const timer = setInterval(() => {
        if (this.state.countdown === 1) {
          this.setState({
            popupVisible: false,
          });
          clearInterval(timer);
          this.props.history.push('/dashboard');
        } else {
          this.setState({
            countdown: this.state.countdown - 1,
          });
        }
      }, 1000);
    } else {
      this.setState({
        popupVisible: true,
        bindingStatus: 2,
      });
    }
  }

  render () {
    return (
      <Popup
        visible={this.state.popupVisible}
        bindingStatus={this.state.bindingStatus}
        countdown={this.state.countdown}
      />);
  }
}

WebBind.propTypes = {
  location: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired,
};

export default withRouter(WebBind);
